<?php

/*
 * convert category level 1
 * input: {puid = 0}
 * output: {cs.id, cs.name, cd.cid, cd.name} //catsource.cid & catsource.name &catdestination.cid
 */

function convertCategoryLevel1($uid=0){
    global $connect_mayphatdien, $connect_mptgiare;
    $arr_return = array(
        'cs'=>array(
            'id' => '',
        ),
        'cd'=>array(
            'id' => ''
        ),
    );
    
    $source_sql = 'SELECT c.cid as catID,c.image as catImg, c.sort_order as catOrder, c.published as published,  cl.name as catName
        FROM ' . tname('product_categories') . ' c
        INNER JOIN ' . tname('product_category_languages') . ' cl ON cl.cid = c.cid
        INNER JOIN ' . tname('languages') . ' l ON l.lid = cl.lid
        WHERE  c.upid = 0
        ORDER BY c.sort_order ASC';
    
    //execute source query and get resource
    $result = mysql_query($source_sql, $connect_mayphatdien);
    if(!$result){
        echo 'Error connect'. mysql_error($connect_mayphatdien);
    }
    
    //get cid & name of category
    $arr_tmp=array();
    while($object = mysql_fetch_object($result)){
        
        $arr_tmp['cs']['id'][]     = $object->catID;
        $arr_tmp['cs']['name'][]   = $object->catName;
        $arr_tmp['cs']['img'][]    = $object->catImg;
        $arr_tmp['cs']['order'][]  = $object->catOrder;
        $arr_tmp['cs']['published'][] = $object->published;
        
        //for return
        $arr_return['cs']['id'][] = $object->catID;
    }
    
    
    //câu query để export to mayphatdiengiare.vn
    
    foreach($arr_tmp['cs']['id'] as $index => $item){
        
        $name       = $arr_tmp['cs']['name'][$index];
        $image      = $arr_tmp['cs']['image'][$index];
        $ordering   = $arr_tmp['cs']['order'][$index];
        $published  = $arr_tmp['cs']['published'][$index];
        
        $dest_query = "INSERT INTO `nhadat_w_categories` (`id`, `parentid`, `name`, `image`, `ordering`, `published`) VALUES (NULL, '0', '$name', '$image','$ordering', '$published')";
        $result = mysql_query($dest_query, $connect_mptgiare);
        if(!$result){
            echo 'sommething error!'.mysql_error($connect_mptgiare); die;
        }
        
        $arr_return['cd']['id'][] = mysql_insert_id($connect_mptgiare);
        
    }
    
    //execute dest query and get resource
    debug($arr_return);
    return $arr_return;
}


/**
 * Convert category lvl 2
 * query dữ liệu có trong product_categories, product_category_languages, languages,  có upid = cat_id trong  $arr
 * => được 1 danh sách dạng
 *  $arr_return [$catid] => id_child =>array(
 *                                  id, name, published, image
 *                              )
 * @param type $arr 
 */
function convertCategoryLevel2($arr){
    
    global $connect_mayphatdien, $connect_mptgiare;
    $arr_return = array(
        
    );
    
    //get
    foreach($arr['cs']['id'] as $id){
        $source_sql = 'SELECT c.cid as catID,c.image as catImg, c.sort_order as catOrder, c.published as published,  cl.name as catName
            FROM ' . tname('product_categories') . ' c
            INNER JOIN ' . tname('product_category_languages') . ' cl ON cl.cid = c.cid
            INNER JOIN ' . tname('languages') . ' l ON l.lid = cl.lid
            WHERE  c.upid = '.$id.'
            ORDER BY c.sort_order ASC';
        
        //execute source query and get resource
        $result = mysql_query($source_sql, $connect_mayphatdien);
        if(!$result){
            echo 'Error connect'. mysql_error($connect_mayphatdien); die;
        }
        
         //get cid & name of category
        while($object = mysql_fetch_object($result)){
         
            $arr_tmp[$id][$object->catID]['catID']  = $object->catID;
            $arr_tmp[$id][$object->catID]['catName']  = $object->catName;
            $arr_tmp[$id][$object->catID]['catImg']  = $object->catImg;
            $arr_tmp[$id][$object->catID]['catOrder']  = $object->catOrder;
            $arr_tmp[$id][$object->catID]['published']  = $object->published;
            
          
        }//#w:0
    }//#foe:0
    
   
   foreach($arr_tmp as $catId1 => $dataCat1){
       
//       //get name source cat
//       $tmp = array_keys($arr['cs']['id'],$catId1); //return key
//       $nameSourceCat = $arr['cd']['name'][$tmp];
       
       $key = end(array_keys($arr['cs']['id'],$catId1));
       
       $desCatId = $arr['cd']['id'][$key];
       foreach ($dataCat1 as $catId2 => $dataCat2){
           
           //set cat source 
           $arr_return['cs']['id'][] = $catId2;
           
            $name       = $dataCat2['catName']  ;
            $image      = $dataCat2['catImg']   ;
            $ordering   = $dataCat2['catOrder'] ;
            $published  = $dataCat2['published'];

           //câu query để export to mayphatdiengiare.vn
           $dest_query = "INSERT INTO `nhadat_w_categories` (`id`, `parentid`, `name`, `image`, `ordering`, `published`) VALUES (NULL, '$desCatId', '$name', '$image','$ordering', '$published')";
           $result = mysql_query($dest_query, $connect_mptgiare);
           
           if(!$result){
               echo 's$ommething error!'.mysql_error($connect_mptgiare); die('Phải làm lại thôi');
           }else{
               
               //move image to new place
                $file_name  = $image;
                $source_dir = 'd:\\xampp\\htdocs\\mayphatdien.com\\attachment\\products\\';
                $dest_dir   = 'd:\\xampp\\htdocs\\mayphatdiengiare.vn\\images\\cate_pro\\';
                move_picture ($filename, $source_dir, $dest_dir);
           }
           
           $arr_return['cd']['id'][] = mysql_insert_id($connect_mptgiare);           
       }
   }
    
    //get cd
    debug($arr_return);
    return $arr_return;
    
    
}

/*
 * convert Product
 * import 2 table product & image
 */

function convertProduct($arr){
    global $connect_mayphatdien, $connect_mptgiare;
    
    $query = '  SELECT p.cid as cid, p.sku as sku, p.price as price, p.published as published, p.congsuat as congsuat, 
                p.congsuat_line as congsuat_line, p.vo as vo, p. dienthe as dienthe, p.image as image,
                p.xuatxu as xuatxu, p.quymo as quymo, p.bode as bode, p.is_hot as is_hot, p.type as type, 
                p.loaitiente as loaitiente, pl.name as name, pl.summary as summary, pl.description as description,
                pl.seo_title as seo_title, pl.seo_keywords as seo_keywords, pl.seo_description as seo_description
                
                FROM vinacode_products p
                INNER JOIN vinacode_product_languages pl ON pl.pid = p.pid
                INNER JOIN vinacode_languages l ON l.lid = pl.lid
                INNER JOIN vinacode_product_category_languages cl ON cl.cid = p.cid
                AND cl.lid = l.lid
                WHERE l.lid =1
                ORDER BY p.pid DESC';
    
    $result = mysql_query($query, $connect_mayphatdien);
    
    if(!$result){
        die('Cannot query! '.mysql_error($connect_mayphatdien));
    }
    
    var_dump($result);
    
    
    //thực hiện việc tri vấn database ở source file ở trang $connect_mayphatdien
    while($object = mysql_fetch_object($result)){
        
        //chuyễn dữ liệu căn bản
        
        //chuyễn $catid
        $catid = $object->cid;//catid
        $key = end(array_keys($arr['cs']['id'],$catid));
        $catid = $arr['cd']['id'][$key];
        
        $model = $object->sku; //model_21
        $saleprice = $object->price;//saleprice
        $published = $object->published; //published
        $congsuat = $object->congsuat; //congsuat_22
        $congsuatduphong = $object->congsuat_line; //Cong_suat_du_phong_34
        
        //chuyễn võ
        /**
         * Trần
            Cách Âm
         */
        $vo = $object->vo; //vo_28
        if($vo == '1'){
            $vo = '0'; 
        }else if($vo == 2){ //$vo == 2
            $vo = '1';
        }else{
            $vo = '-1';
        }
        
        //chuyễn điện thế
        /**
         * 3 pha
           1 pha
         */
        $dienthe = $object->dienthe; //dien_the_25
        if($dienthe == '1'){
            $dienthe = 0; //'3 pha';
        }else if($dienthe == '2'){
            $dienthe = 1; //'1 pha';
        }else {
            $dienthe = '-1';
        }
        
        //chuyễn xuất xứ
        /**
         * China
            Korea
            USA
            Germany
            England
            Japan
            Việt Nam
         */
        $xuatxu = $object->xuatxu; //xuat_xu_29
        switch ($xuatxu) {
            case '1':
                $xuatxu = '0'; //China
                break;
            case '2':
                $xuatxu = '1';//Korea
                break;
            case '3':
                $xuatxu = '2'; //USA
                break;
            case '4':
                $xuatxu = '3'; //Germany
                break;
            case '5':
                $xuatxu = '4'; //England
                break;
            case '6':
                $xuatxu = '5'; //Japan;
                break;
            case '7':
                $xuatxu = '6'; //Việt Nam;
                break;
            default:
                $xuatxu = '-1'; //Việt Nam;
            break;
        }
        
        /**
         * Gia Đình
            Cao Ốc
            Sản Suất
            Trường Học
         */
        
        $quymo = $object->quymo; //quy_mo_30
        switch ($quymo) {
            case '1':
                $quymo = '0';  //Gia Đình
                break;
            case '2':
                $quymo = '1';  //Cao Ốc
                break;
            case '3':
                $quymo = '2';  //Sản Suất
                break;
            case '4':
                $quymo = '3'; //Trường Học
                break;
            default:
                $quymo = '-1'; //Trường Học
                break;
        }
        
        //chọn bộ đề
        /**
         * Có
            Không
         */
        $bode = $object->bode;//Bo_de_20
        switch ($bode) {
            case '1':
                $bode = 0; //'Có';
                break;
            case '2':
                $bode = 1; //'Không';
                break;
            default:
                $bode = -1; //'Không';
                break;
        }
        
        //chọn nhiên liệu
        /**
         * Diesel
            Xăng
         */
        $nhienlieu = $object->is_hot; //Nhien_lieu_23
        switch ($nhienlieu) {
            case '2':
                $nhienlieu = 0;//'Diesel';
                break;
            
            case '3':
                $nhienlieu = 1; //'Xăng';
                break;
            
            default: 
                $nhienlieu = -1; //'Xăng';
                break;
        }
        
        //chọn loại máy
        /**
         * Máy mới
           Máy cũ
         */
        $loaimay = $object->type; //Loai_may_24
        switch ($loaimay) {
            case '1':
                $loaimay = 0; //'Máy mới';
                break;
            
            case '2':
                $loaimay = 1; //'Máy cũ';
                break;
            default :
                $loaimay = -1; //'Máy cũ';
                break;
        }
        
        //chuyễn giá mới
        $status = '';
        if(is_string($saleprice)){
            $status = $saleprice;
            $saleprice = '';
        }
        
        $loaitiente = $object->loaitiente; //currency
        
        $name = $object->name; //name
        
        $summary = $object->summary;//shortdesc
        
        $description = $object->description; //description
        
        $seo_title = $object->seo_title; //seo_title_31
        
        $seo_keywords = $object->seo_keywords; //seo_keywords_32
        
        $seo_description= $object->seo_description; //seo_description_33
        
        
        //escape string
        $summary = mysql_real_escape_string($summary);
        $description = mysql_real_escape_string($description);
        
        //thực hiện insert vào product page
        $query = "INSERT INTO  `nhadat_mayphatdiengiare.vn`.`nhadat_w_products` (
            `catid` ,
            `name` ,
            `newprice` ,
            `status`,
            `currency` ,
            `shortdesc` ,
            `description` ,
            `published` ,
            `Bo_de_20` ,
            `Model_21` ,
            `Cong_suat_22` ,
            `Nhien_lieu_23` ,
            `Loai_may_24` ,
            `dien_the_25` ,
            `Vo_28` ,
            `Xuat_xu_29` ,
            `Quy_Mo_30` ,
            `seo_title_31` ,
            `seo_keywords_32` ,
            `seo_description_33` ,
            `Cong_suat_du_phong_34`
            )
            VALUES (
            '$catid',
            '$name',
            '$saleprice',
            '$status',
            '$loaitiente',
            '$summary',
            '$description',
            '$published',
            '$bode',
            '$model',
            '$congsuat',
            '$nhienlieu',
            '$loaimay',
            '$dienthe',
            '$vo',
            '$xuatxu',
            '$quymo',
            '$seo_title',
            '$seo_keywords',
            '$seo_description',
            '$congsuatduphong'
            );
             ";
        $check= mysql_query($query, $connect_mptgiare);
        
        if(!$check){
            echo ('Error when query'. mysql_error($connect_mptgiare). $name);
        }
        
        //chuyễn image cho table image nữa
        /**
         * image of nhadat_phatdien => trong image
         */
        $product_id = mysql_insert_id($connect_mptgiare);
        $image = $object->image;
        $path_file = 'd:\\xampp\\htdocs\\mayphatdien.com\\attachment\\products\\'.$image;
        if(!file_exists($path_file)){
            debug($path_file.'  do not exists'); 
            /**
             * Hyundai DHY 20KSE.jpg
             * Hyundai DHY 12KSE.jpg
             * Hyundai DHY 22KSEm.jpg
             */
        }
        
        $query = "
            INSERT INTO `nhadat_w_images` (`proid`,
                                           `filename`,
                                           `ordering`,
                                           `isdefault`,
                                           `published`)
                                            VALUES
                                            (
                                              '$product_id',
                                              '$image',
                                              '0',
                                              '1',
                                              '1'
                                            )
            ";
        $tmp = mysql_query($query, $connect_mptgiare);
        if(!$tmp){
            echo 'Insert query wrong query '.mysql_error($connect_mptgiare);
        }
    }
}

/**
 * move picture from old place to new place
 * @param $filename example menu.jpg
 * @param $source_dir exampel c:/system/
 * @param $dest_dir like $source_dir
 */
function move_picture($filename, $source_dir, $dest_dir){
    $return = false;
    
    if(!file_exists($source_dir)){
        mkdir($source_dir);
        echo "$source_dir not exists!";
    }
    
    if(!file_exists($dest_dir)){
        mkdir($dest_dir);
        echo "$dest_dir not exists!";
    }
    
    if(file_exists($source_dir.$filename)){
       if(@copy($source_dir.$filename, $dest_dir.$filename)){
           $return = true;
       }
       
    }else{
        echo "$source_dir.$filename not exists!!!!";
    }
    return $return;
}


function create_machinh($name, $vo, $dien_the, $bo_de, $nhien_lieu){
    $tmp_vo = '';
    if(trim($vo) == '1'){
        $tmp_vo = 'C';
    }else{
        $tmp_vo = 'R';
    }
    
    $tmp_dien_the = '';
    
    if(trim($dien_the) == '1'){
        $tmp_dien_the = '1';
    }else{
        $tmp_dien_the = '3';
    }
    
    $tmp_bo_de = '';
    if(trim($bo_de) == '1'){
        $tmp_bo_de = 'S';
    }else{
        $tmp_bo_de = '0';
    }
    
    $tmp_nhien_lieu = '';
    if(trim($nhien_lieu) == '1'){
        $tmp_nhien_lieu = 'F';
    }else{
        $tmp_nhien_lieu = 'D';
    }
    
    return $name." ".$tmp_vo.$tmp_dien_the.$tmp_bo_de.$tmp_nhien_lieu;
}

function process_machinh($arr_sanpham){
    global $connect_mptgiare;
    
    
    $in_catid =  "('".implode("','",$arr_sanpham)."')";
    $query = "SELECT * FROM `nhadat_w_products` where catid in $in_catid";
    
    $result = mysql_query($query, $connect_mptgiare);
    
    if(!$result){
        die('Cannot query! '.mysql_error($connect_mptgiare));
    }
    
    var_dump($result);
    
    $arr_nedata = array(); //not enough data;
    
    while($object = mysql_fetch_object($result)){
        
        //tên
        $name = $object->name;
        
        //vo Vo_28
        $vo = $object->Vo_28;
        
        //dien the dien_the_25
        $dien_the = $object->dien_the_25;
        
        //bo de Bo_de_20
        $bo_de = $object->Bo_de_20;
        
        //nhien lieu Nhien_lieu_23
        $nhien_lieu = $object->Nhien_lieu_23;
        
        
        //giử lại tất cả những row mà thiếu dữ liệu để xữ lý riêng
        if($vo == '-1' || $dien_the == '-1' || $bo_de == '-1' || $nhien_lieu == '-1'){
            $arr_nedata[] = $object->id;
            continue;
        }
        
        $machinh = create_machinh($name, $vo, $dien_the, $bo_de, $nhien_lieu);
        
        $query = 'UPDATE `nhadat_w_products` set `machinh` = "'.$machinh.'" where id= "'.$object->id.'"';
        
        $tmp = mysql_query($query, $connect_mptgiare);
        if(!$tmp){
            echo 'Insert query wrong query '.mysql_error($connect_mptgiare);
        }
    }
    
    //unpublish tất cả các dòng không hoàng chỉnh
//    foreach($arr_nedata as $index => $id){
//        $query = "UPDATE `nhadat_w_products` set published = 0 where id = '$id'";
//        
//        $tmp = mysql_query($query, $connect_mptgiare);
//        if(!$tmp){
//            echo 'Insert query wrong query '.mysql_error($connect_mptgiare);
//        }
//    }
}


function debug($arr){
    echo '<pre>';
    print_r($arr);
    echo '</pre>';
}




function tname($string){    
    $prefix = 'vinacode_';
    $return = $prefix.$string;
    return $return;
}


